// 简化的用户数据模型
interface User {
  id: string;
  username: string;
  password: string;
  realName: string;
  age: number;
  gender: string;
  role: 'patient' | 'doctor';
  createdAt?: Date;
  lastLogin?: Date;
}

// 用户服务类 - 简化版本
export class UserService {
  private static instance: UserService;
  private currentUser: User | null = null;

  // 单例模式
  public static getInstance(): UserService {
    if (!UserService.instance) {
      UserService.instance = new UserService();
    }
    return UserService.instance;
  }

  // 简化的密码哈希函数
  private hashPassword(password: string): string {
    // 简单的哈希实现，用于演示
    let hash = 0;
    for (let i = 0; i < password.length; i++) {
      const char = password.charCodeAt(i);
      hash = ((hash << 5) - hash) + char;
      hash = hash & hash;
    }
    return hash.toString(36);
  }

  // 用户注册 - 简化版
  async register(userData: Omit<User, 'id'>, profileData?: any): Promise<User | null> {
    try {
      // 模拟用户名检查
      if (userData.username === 'test') {
        console.error('用户名已存在');
        return null;
      }

      // 创建新用户
      const newUser: User = {
        ...userData,
        id: Date.now().toString() + Math.random().toString(36).substr(2, 9),
        password: this.hashPassword(userData.password),
        createdAt: new Date(),
        lastLogin: new Date()
      };

      // 在内存中保存当前用户
      this.currentUser = newUser;
      console.log('用户注册成功:', newUser.username);
      return newUser;
    } catch (error) {
      console.error('用户注册失败:', error);
      return null;
    }
  }

  // 用户登录 - 简化版
  async login(username: string, password: string): Promise<User | null> {
    try {
      // 模拟登录验证
      if (username === 'test' && password === 'password') {
        // 返回测试用户
        this.currentUser = {
          id: 'test123',
          username: username,
          password: this.hashPassword(password),
          realName: '测试用户',
          age: 30,
          gender: 'male',
          role: 'patient',
          lastLogin: new Date()
        };
        console.log('用户登录成功:', username);
        return this.currentUser;
      } else {
        console.error('用户名或密码错误');
        return null;
      }
    } catch (error) {
      console.error('用户登录失败:', error);
      return null;
    }
  }

  // 获取当前用户
  getCurrentUser(): User | null {
    return this.currentUser;
  }

  // 用户登出
  logout(): void {
    this.currentUser = null;
    console.log('用户已登出');
  }
}

export default UserService;